﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using SmartProject.Exceptions;

namespace SmartProject.BusinessRules
{
    public class EMailAsUserName : BusinessRule
    {
        public override string Name
        {
            get { return "E-Mail address as username."; }
        }

        public override string Description
        {
            get { return "Username is the E-Mail address."; }
        }

        public override void Implement(Entity data)
        {
            string email = (string)data.GetAttributeValue("EMail");
            if (data.StoredProc == "smartProject_AddUser")
            {
                // Check if someone else has used this e-mail address.
                string userName = Membership.GetUserNameByEmail(email);
                if (!String.IsNullOrEmpty(userName))
                {
                    throw new Exceptions.BusinessRuleViolation(String.Format(
                        "E-mail address: {0} is already in use.", email));
                }
            }
            else if (data.StoredProc == "smartProject_UpdateUser")
            {
                string originalEmail = (string)data.GetBusinessRuleParameterValue("EMail");
                if (originalEmail != email)
                {
                    // Check and see if the new e-mail address is used by someone else.
                    string userName = Membership.GetUserNameByEmail(email);
                    if (!String.IsNullOrEmpty(userName))
                    {
                        throw new Exceptions.BusinessRuleViolation(String.Format(
                            "E-mail address: {0} is already in use.", email));
                    }
                }
            }
            data.SetAttribute("UserName", email);
        }

        public override bool QueryBooleanProperty(string propertyName)
        {
            switch (propertyName)
            {
                case "IsEnableUserNameTextBox":
                    return false;
            }
            throw new MissingPropertyName(String.Format(
                "Property name is missing: {0}", propertyName));
        }
    }
}
